package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.bean.PageRes;
import com.example.demo.bean.sysrole.SysRoleDO;
import com.example.demo.bean.sysrolemenu.SysRoleMenuDO;
import com.example.demo.exception.OtherException;
import com.example.demo.mapper.sysrole.SysRoleMapper;
import com.example.demo.service.ISysRoleMenuService;
import com.example.demo.service.ISysRoleService;
import com.example.demo.dto.sysrole.SysRolePageReqVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRoleDO> implements ISysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private ISysRoleMenuService sysRoleMenuService;

    @Override
    public PageRes<SysRoleDO> list(SysRolePageReqVO sysRolePageReqVO) {
        return sysRoleMapper.selectPage(sysRolePageReqVO);
    }

    @Override
    public int addSysRole(SysRoleDO sysRoleDO) {
        validRoleCodeExist(sysRoleDO.getRoleCode(), null);
        return sysRoleMapper.insert(sysRoleDO);
    }

    @Override
    @Transactional
    public int deleteSysRole(SysRoleDO sysRoleDO) {
        validExist(sysRoleDO.getId());
        sysRoleMenuService.deleteSysRoleMenuByRoleId(new SysRoleMenuDO().setRoleId(sysRoleDO.getId()));
        return sysRoleMapper.deleteById(sysRoleDO.getId());
    }

    @Override
    public int updateSysRole(SysRoleDO sysRoleDO) {
        validExist(sysRoleDO.getId());
        validRoleCodeExist(sysRoleDO.getRoleCode(), sysRoleDO);
        return sysRoleMapper.updateById(sysRoleDO);
    }

    @Override
    public SysRoleDO getSysRole(SysRoleDO sysRoleDO) {
        validExist(sysRoleDO.getId());
        return sysRoleMapper.selectById(sysRoleDO.getId());
    }

    private void validExist(Long roleId) {
        if (Objects.isNull(sysRoleMapper.selectById(roleId))) {
            throw new OtherException("角色不存在");
        }
    }

    private void validRoleCodeExist(String roleCode, SysRoleDO oldInfo) {
        QueryWrapper<SysRoleDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_code", roleCode);
        if (oldInfo != null) {
            queryWrapper.ne("id", oldInfo.getId());
        }
        SysRoleDO exist = sysRoleMapper.selectOne(queryWrapper);
        if (exist != null) {
            throw new OtherException("角色编码已存在");
        }
    }
}
